package com.mapproject.industrymap.utils;

import org.apache.commons.dbcp.BasicDataSource;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.MultiPolygon;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.FeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.springframework.jdbc.core.JdbcTemplate;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.MalformedInputException;
import java.util.Collection;
import java.util.Iterator;

public class DataItemGeojson2 {
    public String readGeojson(String tableName,String fileName,String path){
        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName("org.postgresql.Driver");
        //basicDataSource.setUrl("jdbc:postgresql://218.93.116.192:5432/industrymap");
        basicDataSource.setUrl("jdbc:postgresql://localhost:5432/WJMap");
        basicDataSource.setUsername("postgres");
        //basicDataSource.setPassword("Wjgh@123");
        basicDataSource.setPassword("lvshuangxi");
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(basicDataSource);
        String resultinfo="";
        String createsql="";
        String insertsql="";
        String insertToPersonSql="";
        ShapefileDataStore shapefileDataStore=null;
        try{
            File shpfile = new File(path);
            shapefileDataStore = new ShapefileDataStore(shpfile.toURI().toURL()) ;
            shapefileDataStore.setCharset(Charset.forName("GBK"));
            //centos字符类型为utf-8
//            shapefileDataStore.setCharset(Charset.forName("UTF-8"));
            String typeName=shapefileDataStore.getTypeNames()[0];
            FeatureType schema=shapefileDataStore.getSchema(typeName);
            String wkid="0";
            CoordinateReferenceSystem srssystem=schema.getCoordinateReferenceSystem();
            try{

                int espg= CRS.lookupEpsgCode(srssystem,true);
                wkid=""+espg;

            }catch (Exception e){
                wkid="0";
            }
            FeatureSource<SimpleFeatureType,SimpleFeature>  featureSource = null;
            featureSource = (FeatureSource<SimpleFeatureType,SimpleFeature>)shapefileDataStore.getFeatureSource(typeName);
            FeatureCollection<SimpleFeatureType,SimpleFeature> result = featureSource.getFeatures();
            FeatureIterator<SimpleFeature> itertor = result.features();
            createsql="DROP TABLE IF EXISTS PUBLIC."+typeName+";";
            createsql+="CREATE TABLE  PUBLIC."+typeName+"(";
            createsql+="gid2 int4  not null,";
            int count=0;
            int sqlcount=0;
            int commitcount=100;
            while(itertor.hasNext()){
                SimpleFeature feature=itertor.next();
                Collection<Property> p=feature.getProperties();
                Iterator<Property> it=p.iterator();
                String geommetry="";
                if(sqlcount==0){
                    insertsql="BEGIN;";
                }
                sqlcount++;
                insertsql+="insert into "+typeName+" values("+count+",";
                while (it.hasNext()){
                    Property pro=it.next();
                    if(pro.getValue() instanceof Point){
                        geommetry="st_geomfromtext('"+((Point)pro.getValue()).toString()+"',"+wkid+")";

                    }else if(pro.getValue() instanceof Polygon){

                        geommetry="st_geomfromtext('"+((Polygon)pro.getValue()).toString()+"',"+wkid+")";
                    }else if(pro.getValue() instanceof MultiPolygon){
                        geommetry="st_geomfromtext('"+((MultiPolygon)pro.getValue()).toString()+"',"+wkid+")";
                    }else if(pro.getValue() instanceof LineString){
                        geommetry="st_geomfromtext('"+((LineString)pro.getValue()).toString()+"',"+wkid+")";
                    }else{
                        if(count==0){
                            createsql+="\""+pro.getName()+"\""+" varchar(250) COLLATE \"default\",";
                        }
                        insertsql+="'"+pro.getValue()+"',";
                    }
                }
                insertsql+=geommetry+");";
                if(count==0){
                    createsql+="geom public.geometry) WITH (OIDS=FALSE);";
                    jdbcTemplate.execute(createsql);
                }
                if(sqlcount==commitcount){
                    insertsql+=" COMMIT;";
                    jdbcTemplate.execute(insertsql);
                    sqlcount=0;
                }
               count++;

            }
            if(sqlcount!=0){
                insertsql+="COMMIT;";
                jdbcTemplate.execute(insertsql);
                //将表记录写入Person表中,考虑到大小写问题，所有的表名和记录均改为小写
                String layer_name = fileName.toLowerCase();
                insertToPersonSql = "INSERT INTO public.personal_data_information(\n" +
                        "\tname, server_url, layer_name, person_name, department_name, layer_style)\n" +
                        "\tVALUES ('"+tableName+"', 'http://localhost:8080/geoserver/WJMap/wms', 'WJMap:"+layer_name+"', '吴国超', '空间信息所', 'polygon');";
                jdbcTemplate.execute(insertToPersonSql);
            }
            itertor.close();
            shapefileDataStore.dispose();
            shpfile.exists();

            resultinfo=typeName;
        }catch (MalformedInputException e ){

        }catch (IOException e){

        }
return resultinfo;
    }





}



